package com.imu.purse.admin.controller.business;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.imu.common.utils.PhoneUtil;
import com.imu.purse.modules.app.service.CoreService;
import com.imu.purse.modules.bitcoin.YtfcoinApi;
import com.imu.purse.modules.trade.task.UserAddressTask;
import com.imu.utils.ShortUUID;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.imu.common.annotation.SysLog;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.utils.R;
import com.imu.common.validator.ValidatorUtils;
import com.imu.common.validator.group.AddGroup;
import com.imu.common.validator.group.UpdateGroup;
import com.imu.constant.Constant;
import com.imu.purse.modules.sys.entity.SysConfigEntity;
import com.imu.purse.modules.sys.service.SysConfigService;
import com.imu.purse.modules.trade.entity.FundEntity;
import com.imu.purse.modules.trade.entity.TradeInfoEntity;
import com.imu.purse.modules.trade.service.FundService;
import com.imu.purse.modules.trade.service.TradeInfoService;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-04-17 10:01:32
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@RestController
@RequestMapping("fund")
public class FundController extends com.imu.purse.modules.sys.controller.AbstractController
{
	private static final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1);

	/****
	 * 查询
	 * @param params
 	 * @date 2018-04-17 10:01:32
	 * @return
	 */
	@SysLog("查询")
	@GetMapping("list")
	@RequiresPermissions("fund:list")
	public R list(@RequestParam Map<String, Object> params)
	{
		R r = R.ok();
		if(CollectionUtils.isEmpty(params)) return r;
		
		FundEntity dto = BeanUtil.mapToBean(params, FundEntity.class, true);
		if(null == dto || StrUtil.isBlank(dto.getP())) return r;
		
		if(null != dto && StrUtil.isBlank(dto.getSts()))
		{
			dto.setSts(DateUtil.beginOfYear(new Date()).toString());
		}
		if(null != dto && StrUtil.isBlank(dto.getEts()))
		{
			dto.setEts(DateUtil.endOfYear(new Date()).toString());
		}
		List<FundEntity> dtos = service.queryList(dto);
		if(CollectionUtils.isEmpty(dtos)) return r;
		
		return r.put("page", new PageInfo<FundEntity>(dtos));
	}
	
	/****
	 * 查询历史资金
	 * @param params
 	 * @date 2018-04-17 10:01:32
	 * @return
	 */
	@GetMapping("hist")
	@RequiresPermissions("fund:hist")
	public R hist(@RequestParam Map<String, Object> params)
	{
		R r = R.ok();
		if(CollectionUtils.isEmpty(params)) return r;
		
		FundEntity dto = BeanUtil.mapToBean(params, FundEntity.class, true);
		if(null == dto || StrUtil.isBlank(dto.getP())) return r;
		
		if(null != dto && StrUtil.isBlank(dto.getSts()))
		{
			dto.setSts(DateUtil.beginOfYear(new Date()).toString());
		}
		if(null != dto && StrUtil.isBlank(dto.getEts()))
		{
			dto.setEts(DateUtil.endOfYear(new Date()).toString());
		}
		List<FundEntity> dtos = service.queryListOld(dto);
		if(CollectionUtils.isEmpty(dtos)) return r;
		
		return r.put("page", new PageInfo<FundEntity>(dtos));
	}
	
	/****
	 * 根据ID查询
	 * @param id
 	 * @date 2018-04-17 10:01:32
	 * @return
	 */
	@SysLog("根据USER_ID查询")
	@GetMapping("/info/userid/{id}")
	@RequiresPermissions("fund:info")
	public R infoByUserId(@PathVariable("id") Long id)
	{
		return R.ok().put("dto", service.findByUserId(id));
	}

    /****
     * 根据ID查询
     * @param id
     * @date 2018-04-17 10:01:32
     * @return
     */
    @SysLog("根据ID查询")
    @GetMapping("/info/{id}")
    @RequiresPermissions("fund:info")
    public R info(@PathVariable("id") Long id)
    {
        return R.ok().put("dto", service.findById(id));
    }
	
	/****
	 * 新增
	 * @param dto
 	 * @date 2018-04-17 10:01:32
	 * @return
	 */
	@SysLog("新增")
	@PostMapping("/save")
	@RequiresPermissions("fund:save")
	public R save(@RequestBody FundEntity dto)
	{
		ValidatorUtils.validateEntity(dto, AddGroup.class);
		//dto.setUserCreate(this.getUserId());
		//dto.setUserUpdate(this.getUserId());
		service.save(dto);
		return R.ok();
	}
	
	/****
	 * 修改
	 * @param dto
 	 * @date 2018-04-17 10:01:32
	 * @return
	 */
	@SysLog("修改")
	@PostMapping("/update")
	@RequiresPermissions("fund:update")
	public R update(@RequestBody FundEntity dto)
	{
		ValidatorUtils.validateEntity(dto, UpdateGroup.class);
		//dto.setUserUpdate(this.getUserId());
		service.update(dto);
		return R.ok();
	}

    /****
     * 修改
     * @param
     * @date 2018-04-17 10:01:32
     * @return
     */
    @SysLog("修改金额")
    @PostMapping("/updateMoney")
    @RequiresPermissions("fund:update:money")
    public R updateMoney(@RequestBody Map<String, Object> params)
    {
        if(null == params || StrUtil.isBlank(params.get("userId").toString())) return R.error(ErrorDesc.PARAM_EMPTY.getCode(), ErrorDesc.PARAM_EMPTY.getMsg());

        FundEntity fund = BeanUtil.mapToBean(params, FundEntity.class, true);
        if(null == fund || null == fund.getYtfType() || null == fund.getMoney()) return R.error(ErrorDesc.PARAM_EMPTY.getCode(), ErrorDesc.PARAM_EMPTY.getMsg());
        if(0 > fund.getYtfType().intValue() || 18 <= fund.getYtfType().intValue()) return R.error(1120, "交易类型有误,请核实.");
        if(0 == fund.getMoney().intValue()) return R.error(1121, "交易数量不能为0");
        
        //易买宝信息归集
  		SysConfigEntity config = sysConfigService.findByKey(Constant.PRI_USER_KEY);
  		Long userId = 0l;
  		if(null != config && StrUtil.isNotBlank(config.getValue()))
  		{
	      	try {
				userId = Long.valueOf(config.getValue());
	      	} 
	      	catch (Exception e) { }
  		}
      
  		if(0 >= userId) return R.error(611, "收款信息不存在,请联系管理员");
  		
        service.updateMoney("user:fund", userId, fund);
        return R.ok();
    }
    
    /****
     * 释放资源
     * @param
     * @date 2018-04-17 10:01:32
     * @return
     */
    @SysLog("释放资源")
    @PostMapping("/release")
    @RequiresPermissions("fund:update:money")
    public R release(@RequestBody Map<String, Object> params)
    {
        if(null == params || StrUtil.isBlank(params.get("userId").toString())) return R.error(ErrorDesc.PARAM_EMPTY.getCode(), ErrorDesc.PARAM_EMPTY.getMsg());

        FundEntity fund = BeanUtil.mapToBean(params, FundEntity.class, true);
        if(null == fund || null == fund.getYtfType()) return R.error(ErrorDesc.PARAM_EMPTY.getCode(), ErrorDesc.PARAM_EMPTY.getMsg());
        if(0 > fund.getYtfType().intValue() || 2 <= fund.getYtfType().intValue()) return R.error(1120, "类型有误,请核实.");
        
        service.release("user:fund:release", fund);
        return R.ok();
    }
	
	/****
	 * 删除
	 * @param ids
 	 * @date 2018-04-17 10:01:32
	 * @return
	 */
	@SysLog("删除")
	@PutMapping("/delete")
	@RequiresPermissions("fund:delete")
	public R delete(@RequestBody String[] ids)
	{
		service.delete(ids);
		return R.ok();
	}
	
	/****
	 * 查询交易表
	 * @param params
 	 * @date 2018-04-17 11:30:06
	 * @return
	 */
	@SysLog("查询交易表")
	@GetMapping("/tradeInfoList")
	@RequiresPermissions("fund:list")
	public R tradeInfoList(@RequestParam Map<String, Object> params)
	{
		R r = R.ok();
		if(CollectionUtils.isEmpty(params)) return r;
		
		TradeInfoEntity dto = BeanUtil.mapToBean(params, TradeInfoEntity.class, true);
		List<TradeInfoEntity> dtos = tradeInfoService.queryLists(dto);
		if(CollectionUtils.isEmpty(dtos)) return r;
		
		return r.put("page", new PageInfo<TradeInfoEntity>(dtos));
	}

	/**
	 * 批量变更用户地址，该功能只是临时将比特币地址更改为以太坊地址
	 * @return
	 */
	@SysLog("变更钱包地址")
	@PutMapping("/updateBatchAddress")
	@RequiresPermissions("fund:updateBatchAddress")
	public R updateAddress(){
		for(int i=0; i<10;i++){
			final int mod = i;
			executor.submit(new Runnable() {
				@Override
				public void run() {
					userAddressTask.handleData(mod);
				}
			});
		}

		return R.ok();
	}

	@SysLog("创建用户钱包地址")
	@PutMapping("/updateYtfAddress")
	@RequiresPermissions("fund:updateYtfAddress")
	public R updateYtfAddress(@RequestBody FundEntity dto){
		if(dto.getId() == null || StrUtil.isEmpty(dto.getPhone())){
			return R.error(-1,"部分值为空");
		}
		//校验ID和phone是否有效
		FundEntity fundEntity = service.findByIdAndPhone(dto);
		if(fundEntity == null){
			return R.error(-1,"无效数据");
		}
		//调用以太坊钱包地址
		String ytfPwd = dto.getPhone() + ShortUUID.shortUUID();
		if(!PhoneUtil.isCPhone(dto.getPhone())){//非手机号码
			ytfPwd = ShortUUID.UUID();
		}
		String moneyAddress = coreService.getCoreAddress();
		String newAddress = ytfcoinApi.createAccount(ytfPwd,moneyAddress);
		if(StrUtil.isEmpty(newAddress)){
			return R.error(-1,"系统繁忙,请稍后再试");
		}
		//修改该用户钱包地址和密码
		dto.setMoneyAddress(newAddress);
		dto.setPassword(ytfPwd);
		service.upAddressById(dto);
		return R.ok();
	}
	@Autowired
	private FundService service;
	
	@Autowired
	private TradeInfoService tradeInfoService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private UserAddressTask userAddressTask;

    @Autowired
    private YtfcoinApi ytfcoinApi;

    @Autowired
    private CoreService coreService;
}
